package com.w3coffee.web.control;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

import com.w3coffee.web.User;
import com.w3coffee.web.dao.CoffeeDao;
import com.w3coffee.web.dao.model.TCheckin;
import com.w3coffee.web.dao.model.TUser;
import com.w3coffee.web.oauth.IOauthApi;
import com.w3coffee.web.oauth.OauthFactory;

public class OauthCallbackController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(getClass());
	/** 签到有效期，30天 */
	private final static int CHECKIN_AVAILABLE_PERIOD = 30 * 24 * 60 * 60;

	@Override
	public ModelAndView handleRequest(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		Map<String, Object> model = getDefaultModel(req);
		String host = trimHost(req.getParameter("host"));
		String token = req.getParameter("oauth_token");
		String verifier = req.getParameter("oauth_verifier");
		OauthFactory factory = (OauthFactory) getBean("oauthFactory");
		IOauthApi authApi = factory.getOAuth(host);
		if (authApi == null) {
			logger.error("OauthApi for [" + host + "] not found.");
			return adaptive(req, resp, "welcome", model);
		} else if (token == null) {
			logger.error("OAuth callback from host [" + host
					+ "] lack of oauth_token parameter.");
			return adaptive(req, resp, "welcome", model);
		} else if (verifier == null) {
			logger.error("OAuth callback from host [" + host
					+ "] lack of oauth_verifier parameter.");
			return adaptive(req, resp, "welcome", model);
		}

		HttpSession session = req.getSession();
		CheckinToken ct = (CheckinToken) session.getAttribute("TOKEN");
		if (ct == null) {
			return adaptive(req, resp, "welcome", model);
		}
		User user = ct.getUser();

		user.setHost(host);
		user.setToken(token);
		user.setVerifier(verifier);
		authApi.doAuth(user);
		
		CoffeeDao dao = (CoffeeDao) getBean("coffeeDao");
		TUser tu = user.getPo();
		int uid = dao.getUserId(tu);
		if (uid > 0) {
			tu.setUid(uid);
			dao.updateUser(tu);
		} else {
			dao.createUser(user.getPo());
		}
		
		TCheckin record = ct.encapsulate(req);
		dao.createCheckinDetail(record);
		
		/* 把登录记录写入cookie */
		Cookie cookie = new Cookie("TOKEN",
				new Integer(record.getId()).toString());
		cookie.setMaxAge(CHECKIN_AVAILABLE_PERIOD);
		resp.addCookie(cookie);

		String targetUrl = (String) session.getAttribute("backUrl");
		
		
		if (targetUrl != null) {
			model.put("targetUrl", targetUrl);
			session.removeAttribute("backUrl");
			return adaptive(req, resp, "redirect", model);
		} else {
			return adaptive(req, resp, "welcome", model);
		}
	}
	
	public String trimHost(String paramValue) {
		StringBuffer buf = new StringBuffer(paramValue);
		int idx;
		while ((idx = buf.indexOf("?")) >= 0) {
			buf.delete(idx, idx + 1);
		}
		
		return buf.toString();
	}
}
